package com.markyao.Interceptor;

import com.alibaba.fastjson.JSON;
import com.markyao.dao.pojo.User;
import com.markyao.service.UserService;
import com.markyao.service.impl.UserServiceImpl;
import com.markyao.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserServiceImpl userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录拦截器
        /*
        1.判断请求路径是否是controller方法(HandlerMethod)
        2.判断token是否为空
        3.验证token,loginService
        4.如果成功放行
         */
        if(!( handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        System.out.println("=================request start===========================");
        String requestURI = request.getRequestURI();
        System.out.println("request uri:{}"+requestURI);
        System.out.println("request method:{}"+request.getMethod());
        System.out.println("token:{}"+ token);
        System.out.println("=================request end===========================");
        if(StringUtils.isBlank(token)){
            //写回提示未登录
           System.out.println("拦截住");
            //说明没有登录,重定向到登录页面
            response.sendRedirect("/web/login.html");
           return false;
        }
        User sysUser = userService.checkT(token);
        if(sysUser==null){
            //写回提示未登录
            System.out.println("拦截住");
            //说明没有登录,重定向到登录页面
            response.sendRedirect("/web/login.html");
            return false;
        }
        //登录验证成功直接放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
